package twitter.client.task;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;

import twitter.client.util.ImageChace;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class ImageDownloadTask extends AsyncTask<String, Void, Bitmap> {
	private ImageView imageView;
	private Context context;
	private String imageUrl;
	private String tag;

	public ImageDownloadTask(ImageView v, Context c) {
		this.imageView = v;
		this.context = c;
		this.tag = this.imageView.getTag().toString();
	}

	@Override
	protected Bitmap doInBackground(String... params) {
		Log.d("ImageDownload", "画像ダウンロード開始");
		Bitmap image = null;
		synchronized (this.context) {
			InputStream in = null;
			try {
				this.imageUrl = params[0];
				URL url = new URL(this.imageUrl);

				in = url.openStream();
				image = BitmapFactory.decodeStream(in);
			} catch (IOException e) {
				Log.e("ImageDownload", "画像ダウンロードエラー", e);
			}
		}

		return image;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		Log.d("ImageDownload", "画像ダウンロード完了");
		if (StringUtils.equals(this.tag, this.imageView.getTag().toString())) {
			if (result != null) {
				this.imageView.setImageBitmap(result);
				ImageChace.setImage(this.imageUrl, result);
			}
		}
	}
}